using System;

namespace MetaView.Core;

/// <summary>
/// 定义了快速二进制转换器的接口，用于将对象转换为字节块，反之亦然。
/// </summary>
public interface IFastBinaryConverter
{
    /// <summary>
    /// 从字节块中读取对象。
    /// </summary>
    /// <param name="byteBlock">包含对象数据的字节块。</param>
    /// <param name="type">要读取的对象的类型。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    /// <returns>从字节块中读取的对象实例。</returns>
    object Read<TByteBlock>(ref TByteBlock byteBlock, Type type) where TByteBlock : IByteBlock;

    /// <summary>
    /// 将对象写入字节块。
    /// </summary>
    /// <param name="byteBlock">将要包含对象数据的字节块。</param>
    /// <param name="obj">要写入的对象实例。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    void Write<TByteBlock>(ref TByteBlock byteBlock, in object obj) where TByteBlock : IByteBlock;
}

/// <summary>
/// 提供了一个抽象类，实现了IFastBinaryConverter接口，用于快速二进制转换。
/// </summary>
/// <typeparam name="T">具体实现类的类型参数。</typeparam>
public abstract class FastBinaryConverter<T> : IFastBinaryConverter
{
    /// <summary>
    /// 通过此实现从字节块中读取对象。
    /// </summary>
    /// <param name="byteBlock">包含对象数据的字节块。</param>
    /// <param name="type">要读取的对象的类型。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    /// <returns>从字节块中读取的对象实例。</returns>
    object IFastBinaryConverter.Read<TByteBlock>(ref TByteBlock byteBlock, Type type)
    {
        return this.Read(ref byteBlock, type);
    }

    /// <summary>
    /// 通过此实现将对象写入字节块。
    /// </summary>
    /// <param name="byteBlock">将要包含对象数据的字节块。</param>
    /// <param name="obj">要写入的对象实例。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    void IFastBinaryConverter.Write<TByteBlock>(ref TByteBlock byteBlock, in object obj)
    {
        this.Write(ref byteBlock, (T)obj);
    }

    /// <summary>
    /// 从字节块中读取对象。必须由具体实现类实现。
    /// </summary>
    /// <param name="byteBlock">包含对象数据的字节块。</param>
    /// <param name="type">要读取的对象的类型。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    /// <returns>从字节块中读取的对象实例。</returns>
    protected abstract T Read<TByteBlock>(ref TByteBlock byteBlock, Type type) where TByteBlock : IByteBlock;

    /// <summary>
    /// 将对象写入字节块。必须由具体实现类实现。
    /// </summary>
    /// <param name="byteBlock">将要包含对象数据的字节块。</param>
    /// <param name="obj">要写入的对象实例。</param>
    /// <typeparam name="TByteBlock">字节块的类型，实现了IByteBlock接口。</typeparam>
    protected abstract void Write<TByteBlock>(ref TByteBlock byteBlock, in T obj) where TByteBlock : IByteBlock;
}